﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace QLNHK.BLL
{
    public partial class HoKhau
    {
        private static string GetMaxSoHoKhau()
        {
            const string spName = "SELECT TOP 1 SoSoHoKhau FROM t_HoKhau ORDER BY SoSoHoKhau DESC";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetSqlStringCommand(spName);

            object val = db.ExecuteScalar(dbCommand);
            return val != null ? val.ToString() : string.Empty;
        }
        public static string GetNewSoSoKhau()
        {
            string maNhanKhau_MoiNhat = HoKhau.GetMaxSoHoKhau();

            return string.Format("{0}", ((string.IsNullOrEmpty(maNhanKhau_MoiNhat) ? 0 : System.Convert.ToInt32(maNhanKhau_MoiNhat)) + 1).ToString("00000000"));
        }

        public static HoKhau LoadBy(int soHoKhau)
        {
            List<HoKhau> collection = SelectCollectionDynamic("SoSoHoKhau=" + soHoKhau, "");
            if (collection.Count > 0)
            {
                return collection[0];
            }
            return null;
        }

        public static DataSet SearchBy(string whereCondition, string orderByExpression)
        {
            const string spName = "p_HoKhau_SearchBy";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@WhereCondition", SqlDbType.NVarChar, whereCondition);
            db.AddInParameter(dbCommand, "@OrderByExpression", SqlDbType.NVarChar, orderByExpression);

            return db.ExecuteDataSet(dbCommand);
        }
        public static DataSet DanhSachNhanKhau(int hhoKhauID)
        {
            const string spName = "p_HoKhau_DanhSachNhanKhau";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@HoKhauID", SqlDbType.Int, hhoKhauID);

            return db.ExecuteDataSet(dbCommand);
        }
    }
}